package com.gxz.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置没有权限跳转的自定义页面
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/success.html").permitAll();
        http.exceptionHandling().accessDeniedPage("/unauth.html");
        http.formLogin()  //自定义编写的登录页面
                .loginPage("/login.html") //登录页面设置
                .loginProcessingUrl("/user/login") //登录访问路径
                .defaultSuccessUrl("/test/index") //登录成功之后,跳转路径
                .permitAll()
                .and().authorizeRequests()
                .antMatchers("/", "/test/hello", "/user/login") //设置那些路径可以直接访问,不需要认证
                .permitAll()
                //当前登录用户,只有具有admins权限才可以这个路径
                //hasAuthority() 方法
                //.antMatchers("/test/index").hasAuthority("admins")
                // hasAnyAuthority() 方法
                //.antMatchers("/test/index").hasAnyAuthority("admins","manager")
                //3. hasRole 方法  ROLE_sale
                //.antMatchers("/test/index").hasRole("sale")
                .antMatchers("/test/index").hasAnyRole("sale", "admins")

                .anyRequest().authenticated()
                .and().csrf().disable();//关闭csrf()仿佛
    }
}
